#include "mainwindow.h"
#include "Tools.h"
#include "apibase.h"
#include "ui_mainwindow.h"

#include <QNetworkReply>
MainWindow::MainWindow(QWidget* parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    rest = new APIBase(this);
    rest->setKnownHeaderName(APIBase::KnownHeaders::ContentType, "application/json");

    for (int i = GET; i < MethodEnd; ++i) {
        ui->cbxMethod->setItemData(i, (Method)i);
    }
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_btnRun_clicked()
{
    ui->txtErrMsg->clear();
    ui->txtResult->clear();

    rest->setBaseUrl(ui->edtURL->text().toUtf8());

    httpRun(ui->cbxMethod->currentData().value<Method>());

    qout << "on_btnRun_clicked";
}

void MainWindow::httpRun(Method type)
{
    QNetworkReply* reply = 0;
    switch (type) {
    case GET: {
        reply = rest->get(QUrl(ui->edtURL->text()));
        break;
    }
    case POST: {
        auto data = ui->txtPostData->toPlainText();
        reply = rest->post(QUrl(ui->edtURL->text()), data.toLocal8Bit());
        break;
    }
    }

    if (!reply)
        return;
    connectNetworkReply(reply);
    connectReplyToErrors(reply);
}

void MainWindow::connectNetworkReply(QNetworkReply* reply)
{
    connect(reply, &QNetworkReply::finished,
        this, &MainWindow::networkReplyFinshSlot);
}

void MainWindow::connectReplyToErrors(QNetworkReply* reply)
{
    connect(reply, SIGNAL(error(QNetworkReply::NetworkError)),
        this, SLOT(handleReplyError(QNetworkReply::NetworkError)));

    connect(reply, &QNetworkReply::sslErrors,
        this, &MainWindow::handleSslErrors);
}

void MainWindow::handleReplyError(QNetworkReply::NetworkError error)
{
    auto reply = qobject_cast<QNetworkReply*>(sender());

    if (!reply)
        return;

    ui->txtErrMsg->setPlainText(reply->errorString());
}

void MainWindow::handleSslErrors(QList<QSslError> errors)
{
    for (auto&& err : errors) {
        ui->txtErrMsg->appendPlainText(err.errorString());
    }
}

void MainWindow::networkReplyFinshSlot()
{
    auto reply = qobject_cast<QNetworkReply*>(sender());

    if (!reply)
        return;

    //    while (!reply->atEnd ()) {
    //        ui->txtResult->appendPlainText (reply->readLine ());

    //    }
    QString str = reply->readAll();
    qout << str;
    ui->txtResult->setText(str);
}
